<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <div style="padding: 20px">
      <BasicForm @register="registerForm">
        <template #actionNames>
          <FormItemRest>
            <Checkbox
              v-model:checked="item['checked']"
              v-for="(item, index) in flowNodes"
              :key="index"
              >{{ item.jobName }}: {{ item.title }}
            </Checkbox>
          </FormItemRest>
        </template>
        <template #deptFields>
          <FormItemRest>
            <Checkbox
              v-model:checked="item['checked']"
              v-for="(item, index) in fieldsOfDept"
              :key="index"
              >{{ item.title }}
            </Checkbox>
          </FormItemRest>
        </template>
        <template #userFields>
          <FormItemRest>
            <Checkbox
              v-model:checked="item['checked']"
              v-for="(item, index) in flowUsers"
              :key="index"
              >{{ item.title }}
            </Checkbox>
          </FormItemRest>
        </template>
        <template #roleDescs="{ model, field }">
          <div>
            <InputTextArea readonly v-model:value="model[field]" />
            <a-button
              @click="handleSuccessSelectRole({ codes: '', codeTexts: '' })"
              class="mt-2 mr-2"
            >
              清空
            </a-button>
            <a-button type="primary" @click="handleSelectRole" class="mt-2">选择</a-button>
          </div>
        </template>
        <template #userRealNames="{ model, field }">
          <div>
            <InputTextArea readonly v-model:value="model[field]" />
            <a-button @click="handleSuccessSelectUser(null)" class="mt-2 mr-2"> 清空 </a-button>
            <a-button type="primary" @click="handleSelectUser" class="mt-2">选择</a-button>
          </div>
        </template>
        <template #way>
          <FormItemRest>
            <Checkbox v-model:checked="dataRef['isMsg']">消息</Checkbox>
            <Checkbox v-model:checked="dataRef['isMail']">邮件</Checkbox>
            <Checkbox v-model:checked="dataRef['isSms']" v-if="flowEdit['isUseSMS']">短信</Checkbox>
          </FormItemRest>
        </template>
        <template #title="{ model, field }">
          <FormItemRest>
            <div style="display: flex; align-items: center">
              <Input v-model:value="model[field]" />
              <Popover>
                <template #content>
                  <div
                    :key="k.value"
                    v-for="k in fields"
                    @click="handleClickMenu(k.value, 'title')"
                    class="cursor-pointer hover:underline"
                  >
                    {{ k.label }}</div
                  >
                </template>
                <DownOutlined style="margin-left: 10px" />
              </Popover>
              <!-- <Dropdown>
                <DownOutlined style="margin-left: 10px" />
                <template #overlay>
                  <Menu @click="({ key }) => handleClickMenu(key, 'title')">
                    <MenuItem :key="k.value" v-for="k in fields">
                      {{ k.label }}
                    </MenuItem>
                  </Menu>
                </template>
              </Dropdown> -->
            </div>
          </FormItemRest>
        </template>
        <template #content="{ model, field }">
          <FormItemRest>
            <div style="display: flex; align-items: center">
              <Input v-model:value="model[field]" />
              <Popover>
                <template #content>
                  <div
                    :key="k.value"
                    v-for="k in fields"
                    @click="handleClickMenu(k.value, 'content')"
                    class="cursor-pointer hover:underline"
                  >
                    {{ k.label }}</div
                  >
                </template>
                <DownOutlined style="margin-left: 10px" />
              </Popover>
            </div>
          </FormItemRest>
        </template>
        <template #flow>
          <Checkbox v-model:checked="dataRef['isFlowShow']">允许从消息中查看</Checkbox>
        </template>
      </BasicForm>
      <SelectUser @register="registerModalSelectUser" @success="handleSuccessSelectUser" />
      <SelectRoleModal @register="registerModalSelectRole" @success="handleSuccessSelectRole" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onMounted, reactive } from 'vue';
  import { Checkbox, Form, Input, Dropdown, Menu, Popover } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useModal } from '/@/components/Modal';
  import { getOacalenderModifyDays, getOacalenderModifyDay } from '/@/api/workOffice/workOffice';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './configurationModal.data';
  import { SelectUser } from '/@/components/CustomComp/index';
  import SelectRoleModal from '../SelectRoleModal.vue';
  import { useFlowStore } from '/@/store/modules/flow';
  import { isArray } from '/@/utils/is';
  import { getFlowTitle } from '/@/api/process/process';
  import { getDepartmentGetNames, getRealNames, getRoleNames } from '/@/api/system/system';
  import {
    getAdminFlowGetActionsForProcessByFlowJson,
    getFormGetFieldsOfUser,
  } from '/@/api/flowManage/flowManage';
  import { DownOutlined } from '@ant-design/icons-vue';
  const FormItemRest = Form.ItemRest;
  const InputTextArea = Input.TextArea;

  interface nodeList {
    internalName: string;
    jobName: string;
    title: string;
  }

  export default defineComponent({
    name: 'DeptModal',
    components: {
      BasicModal,
      BasicForm,
      Checkbox,
      FormItemRest,
      SelectUser,
      SelectRoleModal,
      InputTextArea,
      Input,
      DownOutlined,
      Dropdown,
      Menu,
      MenuItem: Menu.Item,
      Popover,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const useFlow = useFlowStore();
      const flowEdit = computed(() => useFlow.flowEdit);
      const dataRef = ref<Recordable>({});
      const msgProps = ref('');
      const fields = ref<Recordable[]>([]);
      const fieldsOfDept = ref<Recordable[]>([]);
      const flowJson = ref('');
      const formData = ref<Recordable>({});
      const formCode = ref('');
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false, width: '60%' });
        resetFields();
        try {
          dataRef.value = {
            isMsg: true,
            isMail: true,
            isSms: true,
            isFlowShow: true,
          };
          console.log('useFlow.flowEdit', useFlow.flowEdit);
          console.log('useModalInner data', data);
          msgProps.value = useFlow.flowEdit?.msgProps || '';
          fieldsOfDept.value = data?.fieldsOfDept || [];
          flowJson.value = data?.flowJson;
          formCode.value = data?.formCode;
          fields.value = [
            {
              value: '$fromUser',
              label: '当前用户',
            },
            {
              value: '$flowTitle',
              label: '流程标题',
            },
          ];
          if (isArray(data?.fields)) {
            data.fields.forEach((item) => {
              fields.value.push({
                value: item.name,
                label: item.title,
              });
            });
          }
          console.log('fields.value', fields.value);
          // updateSchema([
          //   {
          //     field: 'titleFields',
          //     componentProps: ({ formModel }) => {
          //       return {
          //         options: fields.value,
          //         onChange: (value) => {
          //           console.log('value', value, 'formModel', formModel);
          //           formModel['title'] += value.indexOf('$') == 0 ? value : '{$' + value + '}';
          //         },
          //       };
          //     },
          //   },
          //   {
          //     field: 'contentFields',
          //     componentProps: ({ formModel }) => {
          //       return {
          //         options: fields.value,
          //         onChange: (value) => {
          //           console.log('value', value, 'formModel', formModel);
          //           formModel['content'] += value.indexOf('$') == 0 ? value : '{$' + value + '}';
          //         },
          //       };
          //     },
          //   },
          // ]);
          await getFlowNode();
          await getMsgProp();
        } catch (err) {
          console.log(err);
        }
      });

      const flowUsers = ref<nodeList[]>([]);
      const flowNodes = ref<nodeList[]>([]);
      //获取节点
      const getFlowNode = async () => {
        await getAdminFlowGetActionsForProcessByFlowJson({
          flowJson: flowJson.value,
          internalName: useFlow.flowInfo.curInternalName,
        }).then((res) => {
          flowNodes.value = res || [];
        });
        await getFormGetFieldsOfUser({ formCode: formCode.value }).then((res) => {
          flowUsers.value = res || [];
        });
        console.log('actionNamesactionNames.value111', {
          flowNodes: flowNodes.value,
          flowUsers: flowUsers.value,
        });
      };
      const [
        registerForm,
        { resetFields, setFieldsValue, getFieldsValue, validate, updateSchema },
      ] = useForm({
        labelWidth: 120,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const getTitle = '请选择 (注：流程转交至下一节点时提醒)';

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });

          const values = await validate();
          console.log('values', values);
          formData.value = Object.assign({}, dataRef.value, values);
          console.log('formData', formData.value);

          await setMsgProp();

          closeModal();
          emit('success', values['mode']);
        } catch (err) {
          console.log(err);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      const [registerModalSelectUser, { openModal: openSelectUser }] = useModal();
      //选择用户
      const handleSelectUser = () => {
        let users: Recordable[] = [];
        if (dataRef.value.users) {
          const userNames: String[] = dataRef.value.users.split(',');
          const userRealNames: String[] = dataRef.value.userRealNames.split(',');
          userNames.forEach((item, index) => {
            users.push({
              name: item,
              key: item,
              realName: userRealNames[index],
              title: userRealNames[index],
            });
          });
        }
        openSelectUser(true, {
          users,
        });
      };
      //选择用户回调
      const handleSuccessSelectUser = (users: Recordable[]) => {
        if (users && users.length) {
          let userNames: String[] = [];
          let keys: String[] = [];

          users.forEach((item) => {
            userNames.push(item.title);
            keys.push(item.key);
          });
          dataRef.value.userRealNames = userNames.join(',');
          dataRef.value.users = keys.join(',');
          setFieldsValue({ userRealNames: dataRef.value.userRealNames });
        } else {
          dataRef.value.userRealNames = '';
          dataRef.value.users = '';
          setFieldsValue({ userRealNames: dataRef.value.userRealNames });
        }
      };

      //选择角色
      const [registerModalSelectRole, { openModal: openSelectRole }] = useModal();
      //选择角色
      const handleSelectRole = () => {
        let targetKeys = [];
        if (dataRef.value.roles) {
          targetKeys = dataRef.value?.roles ? dataRef.value.roles.split(',') : [];
        }
        openSelectRole(true, {
          record: {
            targetKeys,
          },
        });
      };
      //选择角色回调
      const handleSuccessSelectRole = ({ codes, codeTexts }) => {
        dataRef.value.roles = codes;
        dataRef.value.roleDescs = codeTexts;
        setFieldsValue({
          roleDescs: dataRef.value.roleDescs,
        });
      };

      const getMsgProp = () => {
        console.log('msgProps.value', msgProps.value);
        console.log('actionNamesactionNames.value', {
          flowNodes: flowNodes.value,
          flowUsers: flowUsers.value,
        });
        if (!msgProps.value) return;
        let xml;
        try {
          xml = $.parseXML(msgProps.value);
        } catch (e) {}

        if (xml == null) {
          return;
        }

        let $xml = $(xml);
        $xml
          .find('actions')
          .children()
          .each(async function (i) {
            if ($(this).attr('internalName') == useFlow.flowInfo?.curInternalName) {
              let actionNames = $(this).find('actionNames').text();
              let deptFields = $(this).find('deptFields').text();
              let userFields = $(this).find('userFields').text();
              let title = $(this).find('title').text();
              let content = $(this).find('content').text();

              let users = $(this).find('users').text();
              let roles = $(this).find('roles').text();
              dataRef.value['users'] = users || '';
              dataRef.value['roles'] = roles || '';

              let isMsg = $(this).find('isMsg').text();
              let isMail = $(this).find('isMail').text();
              let isSms = $(this).find('isSms').text();
              let isFlowShow = $(this).find('isFlowShow').text();
              if (actionNames) {
                let aNames = actionNames.split(',');
                flowNodes.value.forEach((item) => {
                  item['checked'] = aNames.includes(item['internalName']);
                });
              }
              // if (aNames != null) {
              //   for (i = 0; i < aNames.length; i++) {
              //     setCheckboxChecked('actionNames', aNames[i]);
              //   }
              // }
              if (deptFields) {
                let dNames = deptFields.split(',');
                fieldsOfDept.value.forEach((item) => {
                  item['checked'] = dNames.includes(item['name']);
                });
              }
              // let dNames = deptFields.split(',');
              // if (dNames != null) {
              //   for (i = 0; i < dNames.length; i++) {
              //     setCheckboxChecked('deptFields', dNames[i]);
              //   }
              // }
              if (userFields) {
                let uNames = userFields.split(',');
                flowUsers.value.forEach((item) => {
                  item['checked'] = uNames.includes(item['name']);
                });
              }
              // if (uNames != null) {
              //   for (i = 0; i < uNames.length; i++) {
              //     setCheckboxChecked('userFields', uNames[i]);
              //   }
              // }
              dataRef.value['title'] = title ? title.split(',') : [];
              dataRef.value['content'] = content ? content.split(',') : [];

              let mode = $(this).find('mode').text();
              dataRef.value['mode'] = mode || '1';

              if (isMsg == 'true') {
                dataRef.value['isMsg'] = true;
              } else {
                dataRef.value['isMsg'] = false;
              }
              if (isMail == 'true') {
                dataRef.value['isMail'] = true;
              } else {
                dataRef.value['isMail'] = false;
              }
              if (isSms == 'true') {
                dataRef.value['isSms'] = true;
              } else {
                dataRef.value['isSms'] = false;
              }
              if (isFlowShow == 'true') {
                dataRef.value['isFlowShow'] = true;
              } else {
                dataRef.value['isFlowShow'] = false;
              }
              if (dataRef.value['roles'] && dataRef.value['roles'].trim()) {
                const res = await getRoleNames({ codes: dataRef.value['roles'] });
                dataRef.value['roleDescs'] = res.join(',');
              }
              if (dataRef.value['users'] && dataRef.value['users'].trim()) {
                const res = await getRealNames({ userNames: dataRef.value['users'] });
                if (isArray(res)) {
                  dataRef.value['userRealNames'] = res.join(',');
                }
              }
              // if (o('users').value.trim() != '') {
              //   $.get(
              //     '<%=request.getContextPath()%>/visual/module_msg_prop.jsp',
              //     {
              //       op: 'getUserNames',
              //       users: o('users').value,
              //     },
              //     function (data) {
              //       o('userRealNames').value = data.trim();
              //     },
              //   );
              // }

              // if (o('roles').value.trim() != '') {
              //   $.get(
              //     'getRoleDescs.do',
              //     {
              //       roleCodes: o('roles').value,
              //     },
              //     function (data) {
              //       o('roleDescs').value = data.trim();
              //     },
              //   );
              // }
              console.log('dataRef.value-', dataRef.value);
              setFieldsValue({ ...dataRef.value });
              return false;
            }
          });
      };
      const setMsgProp = () => {
        //     String[] actions = ParamUtil.getParameters(request, "actionNames");
        // String[] deptFields = ParamUtil.getParameters(request, "deptFields");
        // String[] userFields = ParamUtil.getParameters(request, "userFields");
        // String users = ParamUtil.get(request, "users");
        // String roles = ParamUtil.get(request, "roles");

        // String isMsg = ParamUtil.get(request, "isMsg");
        // String isMail = ParamUtil.get(request, "isMail");
        // String isSms = ParamUtil.get(request, "isSms");
        // String isFlowShow = ParamUtil.get(request, "isFlowShow");

        // String title = ParamUtil.get(request, "title");
        // String content = ParamUtil.get(request, "content");
        const actions = flowNodes.value;
        const deptFields = fieldsOfDept.value;
        const userFields = flowUsers.value;
        let strActions = '';
        if (isArray(actions)) {
          for (let i = 0; i < actions.length; i++) {
            if (actions[i]['checked']) {
              strActions += !strActions
                ? actions[i]['internalName']
                : ',' + actions[i]['internalName'];
            }
          }
        }

        console.log('deptFields', deptFields);
        let strDepts = '';
        if (isArray(deptFields)) {
          for (let i = 0; i < deptFields.length; i++) {
            if (deptFields[i]['checked'] && deptFields[i]['name']) {
              strDepts += !strDepts ? deptFields[i]['name'] : ',' + deptFields[i]['name'];
            }
          }
        }

        let strUsers = '';
        if (isArray(userFields)) {
          for (let i = 0; i < userFields.length; i++) {
            if (userFields[i]['checked'] && userFields[i]['name']) {
              strUsers += !strUsers ? userFields[i]['name'] : ',' + userFields[i]['name'];
            }
          }
        }

        console.log('formData.value', formData.value);

        let sb = ''; //new StringBuilder();
        sb = '<action internalName="' + useFlow.flowInfo.curInternalName + '">\r\n';
        sb += '<actionNames>' + strActions + '</actionNames>\r\n';
        sb += '<deptFields>' + strDepts + '</deptFields>\r\n';
        sb += '<userFields>' + strUsers + '</userFields>\r\n';
        sb += '<mode>' + formData.value['mode'] + '</mode>\r\n';
        sb += '<users>' + (formData.value['users'] ? formData.value['users'] : '') + '</users>\r\n';
        sb += '<roles>' + (formData.value['roles'] ? formData.value['roles'] : '') + '</roles>\r\n';
        sb += '<title>' + (formData.value['title'] ? formData.value['title'] : '') + '</title>\r\n';
        sb +=
          '<content>' +
          (formData.value['content'] ? formData.value['content'] : '') +
          '</content>\r\n';
        sb += '<isMsg>' + formData.value['isMsg'] + '</isMsg>\r\n';
        sb += '<isSms>' + formData.value['isSms'] + '</isSms>\r\n';
        sb += '<isMail>' + formData.value['isMail'] + '</isMail>\r\n';
        sb += '<isFlowShow>' + formData.value['isFlowShow'] + '</isFlowShow>\r\n';
        sb += '</action>\r\n';
        console.log('sb', sb);
        // <textarea id="xmlContent" style="display:none"><%=sb.toString() %></textarea>
        // <script>
        let xml = msgProps.value; //window.opener.getMsgProp();
        if (xml == '') {
          xml = '<actions></actions>';
        }
        try {
          xml = $.parseXML(xml);
        } catch (e) {
          alert(e);
        }

        let $xml = $(xml);
        $xml
          .find('actions')
          .children()
          .each(function (i) {
            if ($(this).attr('internalName') == useFlow.flowInfo.curInternalName) {
              $(this).remove();
              return false;
            }
          });

        var $elem = $($.parseXML(sb)); //o("xmlContent").value
        var newNode = null;
        if (typeof document.importNode == 'function') {
          newNode = document.importNode($elem.find('action').get(0), true);
        } else {
          newNode = $elem.find('action').get(0);
        }
        $xml.find('actions').get(0).appendChild(newNode);
        msgProps.value = $xml.xml();
        useFlow.setFlowEdit({ ...useFlow.flowEdit, msgProps: unref(msgProps) });
        console.log('保存成功', msgProps.value);
        // window.opener.setMsgProp($xml.xml());
      };
      // function setCheckboxChecked(checkboxname, v) {
      //   let checkboxboxs = document.getElementsByName(checkboxname);
      //   if (checkboxboxs != null) {
      //     // 如果只有一个元素
      //     if (checkboxboxs.length == null) {
      //       if (checkboxboxs.value == v) {
      //         checkboxboxs.checked = true;
      //       }
      //     }
      //     // for (i = 0; i <script checkboxboxs.length; i++) {
      //     //   if (checkboxboxs[i].type == 'checkbox' && checkboxboxs[i].value == v) {
      //     //     checkboxboxs[i].checked = true;
      //     //   }
      //     // }
      //   }
      // }

      //设置值
      const handleClickMenu = (value, col) => {
        const record = getFieldsValue();
        if (!record[col]) {
          record[col] = '';
        }
        record[col] += value.indexOf('$') == 0 ? value : '{$' + value + '}';
        setFieldsValue({ [col]: record[col] });
      };
      return {
        registerModal,
        getTitle,
        handleSubmit,
        registerForm,
        registerModalSelectUser,
        handleSelectUser,
        handleSuccessSelectUser,
        registerModalSelectRole,
        handleSelectRole,
        handleSuccessSelectRole,
        flowEdit,
        dataRef,
        flowUsers,
        flowNodes,
        fieldsOfDept,
        handleClickMenu,
        fields,
      };
    },
  });
</script>
